import * as historyDataService from '@/services/historyData';

export default {
  namespace: 'historyData',
  state: {
    h: '',
    names: [],
    lists: [],
    total: 0,
    pageNo: 1,
    pageSize: 5,
    startTime: '',
    endTime: ''
  },
  reducers: {
    setData(state, { payload }) {
      return { ...state, ...payload };
    },
  },
  effects: {
    *fetch({ payload: { h, pageNo, startTime, endTime } }, { call, put, select }) {
      const pageSize = yield select(state => state.historyData.pageSize);
      h = h?h:yield select(state => state.historyData.h);
      startTime = startTime?startTime:yield select(state => state.historyData.startTime);
      endTime = endTime?endTime:yield select(state => state.historyData.endTime);
      const response = yield call(historyDataService.fetch, { h, pageNo, pageSize, startTime, endTime });
      if (response && typeof response.state !== undefined && response.state === 0) {
        let total=0, names=[], lists=[];
        response.data.datas.forEach((data)=>{
          names.push(data.name);
          lists.push(data.list);
          total = data.total;
        });
        if(lists.length>1) {
          total = -1;
          pageNo = 1;
        }
        // const { lists, total } = response.data;
        yield put({ type: 'setData', payload: { h, names, lists, total, pageNo, startTime, endTime } });
      } else {
        yield put({
          type: 'setData',
          payload: { h:'', names:[], lists:[], total:0, startTime:'', endTime:''},
        });
      }
    },
  }
}
